package com.example.a001.part29;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

import androidx.appcompat.app.AppCompatActivity;

import com.example.a001.R;


public class VideoPlayerActivity extends AppCompatActivity {

    private VideoView videoView;
    private ProgressBar progressBar;
    private EditText etVideoUrl;
    private Button btnPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        // 初始化控件
        etVideoUrl = findViewById(R.id.etVideoUrl);
        etVideoUrl.setText("https://www.jxyy.edu.cn/__local/C/FC/C2/B6BAEFCE3810D37AAEBCD88A561_1F5AFF3D_6ED42FB6.mp4?e=.mp4");
        btnPlay = findViewById(R.id.btnPlay);
        videoView = findViewById(R.id.videoView);
        progressBar = findViewById(R.id.progressBar);

        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);

        videoView.setMediaController(mediaController);

        // 播放按钮点击事件
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = etVideoUrl.getText().toString().trim();
                if (!url.isEmpty()) {
                    playVideo(url);
                } else {
                    Toast.makeText(VideoPlayerActivity.this, "请输入视频地址", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 设置准备监听器
        videoView.setOnPreparedListener(mp -> {
            progressBar.setVisibility(View.GONE);
            videoView.start();
        });

        // 设置错误监听器
        videoView.setOnErrorListener((mp, what, extra) -> {
            progressBar.setVisibility(View.GONE);
            Toast.makeText(VideoPlayerActivity.this, "视频播放失败", Toast.LENGTH_SHORT).show();
            return true;
        });
    }

    private void playVideo(String url) {
        try {
            Uri uri = Uri.parse(url);
            videoView.setVideoURI(uri);
            progressBar.setVisibility(View.VISIBLE);
            videoView.start();
        } catch (Exception e) {
            progressBar.setVisibility(View.GONE);
            Toast.makeText(this, "无效的视频地址", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}
